import 'dart:convert';
import 'dart:io';

import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/widgets.dart' hide Action;
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:image_picker/image_picker.dart';
import 'package:oktoast/oktoast.dart';
import 'package:school_safe_teacher/base/entity_factory.dart';
import 'package:school_safe_teacher/network/dio_api.dart';
import 'package:school_safe_teacher/network/http_api.dart';
import 'package:school_safe_teacher/user_info/upload_entity.dart';



import 'action.dart';
import 'state.dart';

Effect<SuggestState> buildEffect() {
  return combineEffects(<Object, Effect<SuggestState>>{
    SuggestAction.choosePic: _onChoosePic,
    SuggestAction.cameraPic: _onCameraPic,
    SuggestAction.submit: _onSubmit,
  });
}

Future<void> _onCameraPic(Action action, Context<SuggestState> ctx) async {
  PickedFile pickedFile =
      await ctx.state.picker.getImage(source: ImageSource.camera);
  _uploadPic(pickedFile, ctx);
}

Future<void> _onChoosePic(Action action, Context<SuggestState> ctx) async {
  PickedFile pickedFile =
      await ctx.state.picker.getImage(source: ImageSource.gallery);
  _uploadPic(pickedFile, ctx);
}

Future<void> _onSubmit(Action action, Context<SuggestState> ctx) async {
  if(ctx.state.canSubmit){
    Map<String, String> params = Map();
    params["qtype"] = ctx.state.suggestType.toString();
    params["content"] = ctx.state.content;
    params["imgs"] = jsonEncode(ctx.state.images);
    DioApi.instance.asyncRequestNetwork<dynamic>(
        Method.post, HttpApi.SUGGEST, ctx.context,
        params: params, onStart: () {
      println('请求开始');
      EasyLoading.show();
    }, onSuccess: (dynamic t) async {
      showToast("反馈成功");
      Navigator.of(ctx.context).pop(1);
    }, onError: (String msg) {
      println('请求报错 msg:$msg');
      showToast(msg);
    }, onDone: () {
      EasyLoading.dismiss();
    }, isList: false);
  }else{
    showToast("请填写内容");
  }
}

Future<void> _uploadPic(
    PickedFile pickedFile, Context<SuggestState> ctx) async {
  File file = File(pickedFile.path);
  ctx.state.imageFiles.add(file);
  List<int> imageBytes = await file.readAsBytes();
  String base64 = base64Encode(imageBytes);
  print(base64);
  Map<String, String> params = Map();
  params["image"] = base64;
  DioApi.instance.asyncRequestNetwork<dynamic>(
      Method.post, HttpApi.UP_LOAD_IMAGE, ctx.context, params: params,
      onStart: () {
    println('请求开始');
    EasyLoading.show();
  }, onSuccess: (dynamic t) async {
    UploadEntity entity = EntityFactory.generateOBJ(t);
    ctx.state.images.add(entity.path);
    ctx.dispatch(SuggestActionCreator.onAction());
  }, onError: (String msg) {
    println('请求报错 msg:$msg');
    showToast(msg);
  }, onDone: () {
    EasyLoading.dismiss();
  }, isList: false);
}
